package com.qboot.quartz.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qboot.common.utils.SpringUtils;
import com.qboot.quartz.entity.JobInfo;
import com.qboot.quartz.entity.JobLog;
import com.qboot.quartz.service.JobInfoService;
import com.qboot.quartz.service.JobLogService;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobListener;
import org.springframework.http.HttpStatus;

import java.util.Date;
import java.util.Objects;

/**
 * 定时任务监听
 *
 * @author Tellsea
 * @date 2023/3/2
 */
public class JobLogTriggerListener implements JobListener {

    @Override
    public String getName() {
        return "jobLogTriggerListener";
    }

    @Override
    public void jobToBeExecuted(JobExecutionContext context) {
    }

    @Override
    public void jobExecutionVetoed(JobExecutionContext context) {
    }

    @Override
    public void jobWasExecuted(JobExecutionContext context, JobExecutionException jobException) {
        JobInfoService jobInfoService = SpringUtils.getBean(JobInfoService.class);
        JobLogService jobLogService = SpringUtils.getBean(JobLogService.class);
        String jobName = context.getJobDetail().getKey().getName();
        JobInfo jobInfo = jobInfoService.getOne(new LambdaQueryWrapper<JobInfo>()
                .eq(JobInfo::getJobName, jobName));
        JobLog jobLog = new JobLog();
        jobLog.setJobId(jobInfo.getId());
        jobLog.setTitle(jobInfo.getTitle());
        jobLog.setJobName(jobInfo.getJobName());
        jobLog.setJobGroup(jobInfo.getJobGroup());
        jobLog.setParams(jobInfo.getParams());
        jobLog.setCron(jobInfo.getCron());
        jobLog.setTime(context.getJobRunTime());
        if (Objects.isNull(jobException)) {
            jobLog.setCode(Long.valueOf(HttpStatus.OK.value()));
            jobLog.setResult("执行成功");
        } else {
            jobLog.setCode(Long.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.value()));
            jobLog.setResult(jobException.getMessage());
        }
        jobLog.setRemark(jobInfo.getRemark());
        jobLog.setCreateTime(new Date());
        jobLogService.save(jobLog);
    }
}
